import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  message,
  Tag,
  Row,
  Col,
  Statistic,
  DatePicker,
  Form,
  Input,
  Modal,
  Descriptions,
  Steps
} from 'antd';
import {
  ReloadOutlined,
  SearchOutlined,
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

/**
 * 卡片申请接口定义
 * 用于类型检查，确保卡片申请数据的结构
 */
interface CardApplication {
  id: number;                    // 唯一标识符
  applicationNo: string;         // 申请编号
  applicant: string;             // 申请人姓名
  cardType: string;              // 卡片类型（virtual/physical）
  cardScheme: string;            // 卡组织（visa/mastercard）
  currency: string;              // 货币类型
  status: string;                // 申请状态（pending/processing/approved/rejected）
  applyAmount: number;           // 申请金额
  approvedAmount: number;        // 批准金额
  applyReason: string;           // 申请理由
  reviewer: string;              // 审核人
  reviewOpinion: string;         // 审核意见
  createdAt: string;             // 创建时间
  reviewedAt: string;            // 审核时间
}

/**
 * 卡片申请管理组件
 * 用于展示和处理卡片申请列表，包括查询、审核等功能
 */
const CardApply: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false); // 加载状态
  const [modalVisible, setModalVisible] = useState(false); // 详情模态框显示状态
  const [selectedApplication, setSelectedApplication] = useState<CardApplication | null>(null); // 选中的申请记录
  const [applications, setApplications] = useState<CardApplication[]>([]); // 申请列表数据
  const [queryParams, setQueryParams] = useState({
    dateRange: null as [dayjs.Dayjs | null, dayjs.Dayjs | null] | null, // 时间范围查询条件
    applicationNo: '', // 申请编号查询条件
    applicant: '', // 申请人查询条件
    status: '' // 状态查询条件
  });

  /**
   * 模拟卡片申请数据
   * 在实际项目中，这些数据应该从API获取
   */
  const mockApplications: CardApplication[] = [
    {
      id: 1,
      applicationNo: 'APP202401200001',
      applicant: '张三',
      cardType: 'virtual',
      cardScheme: 'visa',
      currency: 'USD',
      status: 'approved',
      applyAmount: 1000,
      approvedAmount: 1000,
      applyReason: '业务拓展需要',
      reviewer: '李经理',
      reviewOpinion: '申请合理，同意发放',
      createdAt: '2024-01-20T10:30:00Z',
      reviewedAt: '2024-01-20T11:30:00Z'
    },
    {
      id: 2,
      applicationNo: 'APP202401190002',
      applicant: '李四',
      cardType: 'physical',
      cardScheme: 'mastercard',
      currency: 'USD',
      status: 'pending',
      applyAmount: 2000,
      approvedAmount: 0,
      applyReason: '员工福利发放',
      reviewer: '',
      reviewOpinion: '',
      createdAt: '2024-01-19T14:20:00Z',
      reviewedAt: ''
    },
    {
      id: 3,
      applicationNo: 'APP202401180003',
      applicant: '王五',
      cardType: 'virtual',
      cardScheme: 'visa',
      currency: 'EUR',
      status: 'rejected',
      applyAmount: 5000,
      approvedAmount: 0,
      applyReason: '大额项目支出',
      reviewer: '赵总监',
      reviewOpinion: '金额过大，需要补充材料',
      createdAt: '2024-01-18T09:15:00Z',
      reviewedAt: '2024-01-18T10:45:00Z'
    },
    {
      id: 4,
      applicationNo: 'APP202401170004',
      applicant: '赵六',
      cardType: 'physical',
      cardScheme: 'mastercard',
      currency: 'USD',
      status: 'processing',
      applyAmount: 1500,
      approvedAmount: 1500,
      applyReason: '客户礼品卡',
      reviewer: '钱经理',
      reviewOpinion: '符合标准流程',
      createdAt: '2024-01-17T16:45:00Z',
      reviewedAt: '2024-01-17T17:30:00Z'
    }
  ];

  /**
   * 获取卡片申请列表
   * 模拟API调用，实际项目中应替换为真实的API请求
   */
  const fetchApplications = async () => {
    setLoading(true); // 开始加载
    try {
      // 模拟API调用延迟
      setTimeout(() => {
        setApplications(mockApplications); // 设置申请数据
        setLoading(false); // 结束加载
      }, 500);
    } catch (error) {
      console.error('获取卡片申请失败:', error);
      message.error('获取卡片申请失败');
      setLoading(false);
    }
  };

  /**
   * 显示申请详情
   * @param application 选中的申请记录
   */
  const showDetail = (application: CardApplication) => {
    setSelectedApplication(application); // 设置选中的申请
    setModalVisible(true); // 显示详情模态框
  };

  /**
   * 处理批准操作
   * @param application 要批准的申请记录
   */
  const handleApprove = (application: CardApplication) => {
    // 模拟批准操作，实际项目中应调用API
    message.success(`已批准申请 ${application.applicationNo}`);
    fetchApplications(); // 重新获取数据刷新列表
  };

  /**
   * 处理拒绝操作
   * @param application 要拒绝的申请记录
   */
  const handleReject = (application: CardApplication) => {
    // 模拟拒绝操作，实际项目中应调用API
    message.error(`已拒绝申请 ${application.applicationNo}`);
    fetchApplications(); // 重新获取数据刷新列表
  };

  // useEffect钩子：组件挂载时获取申请列表
  useEffect(() => {
    fetchApplications();
  }, []);

  /**
   * 表格列配置
   * 定义表格的列及其渲染方式
   */
  const columns = [
    {
      title: '申请编号',
      dataIndex: 'applicationNo',
      key: 'applicationNo'
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant'
    },
    {
      title: '卡片类型',
      dataIndex: 'cardType',
      key: 'cardType',
      render: (type: string) => {
        // 卡片类型配置映射
        const typeConfig: { [key: string]: { color: string; text: string } } = {
          virtual: { color: 'blue', text: '虚拟卡' },
          physical: { color: 'green', text: '实体卡' }
        };
        const config = typeConfig[type] || { color: 'default', text: type };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '卡组织',
      dataIndex: 'cardScheme',
      key: 'cardScheme',
      render: (scheme: string) => {
        // 卡组织配置映射
        const schemeConfig: { [key: string]: { color: string; text: string } } = {
          visa: { color: 'blue', text: 'Visa' },
          mastercard: { color: 'red', text: 'MasterCard' }
        };
        const config = schemeConfig[scheme] || { color: 'default', text: scheme };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '申请金额',
      dataIndex: 'applyAmount',
      key: 'applyAmount',
      render: (amount: number, record: CardApplication) => (
        <span style={{ fontWeight: 'bold' }}>
          {amount} {record.currency}
        </span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        // 状态配置映射
        const statusConfig: { [key: string]: { color: string; text: string } } = {
          pending: { color: 'orange', text: '待审核' },
          processing: { color: 'blue', text: '处理中' },
          approved: { color: 'green', text: '已批准' },
          rejected: { color: 'red', text: '已拒绝' }
        };
        const config = statusConfig[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString() // 格式化时间显示
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: CardApplication) => (
        <Space>
          {/* 详情按钮 */}
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => showDetail(record)}
          >
            详情
          </Button>
          {/* 只有待审核状态的申请显示批准和拒绝按钮 */}
          {record.status === 'pending' && (
            <>
              <Button
                type="link"
                size="small"
                icon={<CheckOutlined />}
                onClick={() => handleApprove(record)}
                style={{ color: 'green' }}
              >
                批准
              </Button>
              <Button
                type="link"
                size="small"
                icon={<CloseOutlined />}
                onClick={() => handleReject(record)}
                style={{ color: 'red' }}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      )
    }
  ];

  // 统计信息：计算各种状态的申请数量
  const pendingCount = applications.filter(app => app.status === 'pending').length;
  const approvedCount = applications.filter(app => app.status === 'approved').length;
  const rejectedCount = applications.filter(app => app.status === 'rejected').length;

  return (
    <div className="p-6">
      <Card>
        {/* 统计信息卡片 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总申请数"
                value={applications.length}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="待审核"
                value={pendingCount}
                valueStyle={{ color: '#faad14' }} // 橙色显示
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已批准"
                value={approvedCount}
                valueStyle={{ color: '#52c41a' }} // 绿色显示
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已拒绝"
                value={rejectedCount}
                valueStyle={{ color: '#ff4d4f' }} // 红色显示
              />
            </Card>
          </Col>
        </Row>

        {/* 查询表单 */}
        <Card style={{ marginBottom: 16 }}>
          <Form layout="inline">
            <Form.Item label="时间范围">
              <RangePicker
                value={queryParams.dateRange}
                onChange={(dates) => setQueryParams(prev => ({ ...prev, dateRange: dates }))}
              />
            </Form.Item>
            <Form.Item label="申请编号">
              <Input
                placeholder="请输入申请编号"
                value={queryParams.applicationNo}
                onChange={(e) => setQueryParams(prev => ({ ...prev, applicationNo: e.target.value }))}
              />
            </Form.Item>
            <Form.Item label="申请人">
              <Input
                placeholder="请输入申请人"
                value={queryParams.applicant}
                onChange={(e) => setQueryParams(prev => ({ ...prev, applicant: e.target.value }))}
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" icon={<SearchOutlined />}>
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={fetchApplications}>
                  刷新
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 申请记录表格 */}
        <Table
          loading={loading} // 加载状态
          columns={columns} // 列配置
          dataSource={applications} // 数据源
          rowKey="id" // 行键
          pagination={{
            pageSize: 10, // 每页显示10条
            showSizeChanger: true, // 显示每页条数切换器
            showQuickJumper: true, // 显示快速跳转
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条` // 显示总数
          }}
        />

        {/* 详情模态框 */}
        <Modal
          title="卡片申请详情"
          open={modalVisible} // 显示状态
          onCancel={() => setModalVisible(false)} // 取消关闭
          footer={[
            <Button key="close" onClick={() => setModalVisible(false)}>
              关闭
            </Button>
          ]}
          width={700} // 模态框宽度
        >
          {selectedApplication && (
            <>
              {/* 步骤条显示申请进度 */}
              <Steps
                current={
                  selectedApplication.status === 'pending' ? 0 :
                  selectedApplication.status === 'processing' ? 1 :
                  selectedApplication.status === 'approved' ? 2 : 3
                }
                items={[
                  { title: '待审核' },
                  { title: '处理中' },
                  { title: '已批准' },
                  { title: '已拒绝' }
                ]}
                style={{ marginBottom: 24 }}
              />
              
              {/* 详情描述列表 */}
              <Descriptions bordered column={1}>
                <Descriptions.Item label="申请编号">{selectedApplication.applicationNo}</Descriptions.Item>
                <Descriptions.Item label="申请人">{selectedApplication.applicant}</Descriptions.Item>
                <Descriptions.Item label="卡片类型">
                  <Tag color={selectedApplication.cardType === 'virtual' ? 'blue' : 'green'}>
                    {selectedApplication.cardType === 'virtual' ? '虚拟卡' : '实体卡'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="卡组织">
                  <Tag color={selectedApplication.cardScheme === 'visa' ? 'blue' : 'red'}>
                    {selectedApplication.cardScheme.toUpperCase()}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="货币">{selectedApplication.currency}</Descriptions.Item>
                <Descriptions.Item label="申请金额">
                  {selectedApplication.applyAmount} {selectedApplication.currency}
                </Descriptions.Item>
                {selectedApplication.approvedAmount > 0 && (
                  <Descriptions.Item label="批准金额">
                    {selectedApplication.approvedAmount} {selectedApplication.currency}
                  </Descriptions.Item>
                )}
                <Descriptions.Item label="申请理由">{selectedApplication.applyReason}</Descriptions.Item>
                {selectedApplication.reviewOpinion && (
                  <Descriptions.Item label="审核意见">{selectedApplication.reviewOpinion}</Descriptions.Item>
                )}
                {selectedApplication.reviewer && (
                  <Descriptions.Item label="审核人">{selectedApplication.reviewer}</Descriptions.Item>
                )}
                <Descriptions.Item label="申请时间">
                  {new Date(selectedApplication.createdAt).toLocaleString()}
                </Descriptions.Item>
                {selectedApplication.reviewedAt && (
                  <Descriptions.Item label="审核时间">
                    {new Date(selectedApplication.reviewedAt).toLocaleString()}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </>
          )}
        </Modal>
      </Card>
    </div>
  );
};

export default CardApply;